<template>
  <view>
    <!-- 新增的内容区域 -->
    <view class="page">
      <!-- 顶部导航栏 -->
      <up-tabs
        :list="tabList"
        :activeStyle="{
          fontWeight: 'bold',
          transform: 'scale(1.5)',
        }"
        :inactiveStyle="{
          color: '#606266',
          transform: 'scale(1.2)'
        }"
        itemStyle="padding-left: 15px; padding-right: 15px; height: 54px; "
        @change="onTabChange"
      ></up-tabs>

      <!-- 内容区域 -->
      <view class="content-section">
        <view v-for="(section, index) in contentSections" :key="index" class="section">
          <!-- 分类标题 -->
          <view class="section-header">
            <span class="section-title">{{ section.title }}</span>
            <span class="more-btn" @click="handleMore(section.title)">更多></span>
          </view>

          <up-scroll-list>
            <view 
              v-for="(item, subIndex) in section.list" :key="subIndex" 
              @click="playAudio(item,section.title)"
            >
              <view class="item-cover" style="width: 300rpx; margin: 0px 5px;">
                <image :src="item.cover" mode="aspectFill" class="cover-img"></image>
                <view class="play-icon">
                  <up-icon name="play-circle" size="28" color="#4d4d4d"></up-icon>
                </view>
              </view>
              <view class="item-info">
                <text class="item-name">{{ item.name }}</text>
                
                <text class="item-duration">{{ formatDuration(item.duration) }}</text>
                <!-- 使用 @click.stop 阻止事件冒泡 -->
                <view class="control-button" @click.stop="collect(item)">
                  <up-icon :name="item.isCollected === 1 ? `heart-fill` : `heart`" size="30" :color="item.isCollected === 1 ? `#ee0000` : `#398ade`"></up-icon>
                </view>
              </view>
            </view>
          </up-scroll-list>
        </view>
      </view>
       <!-- 新增透明占位组件 -->
       <view style="height: 5vh; opacity: 0;"></view>
    </view>
    <tabbar :index="1"></tabbar>
  </view>
</template>

<script lang="ts" setup>
import { getMusicList } from '@/api/music';
import { ref } from 'vue';
import { toggleCollect } from '@/api/music'; // 引入收藏接口
import type { TabItem, MusicItem, ContentSection } from '@/types/music';
import { onShow } from '@dcloudio/uni-app';

// 数据定义
const currentTab = ref(0); // 默认选中助眠
const tabList: TabItem[] = [
  {
    name: ' 助眠 ',
    title: [
      '助眠经典', '自然音效助眠', '冥想引导助眠'
    ]
  },
  {
    name: ' 放松 ',
    title: [
      '舒缓瑜伽音乐', '深度放松冥想', '轻柔古典音乐', '海洋波浪音效'
    ]
  },
  {
    name: ' 白噪音 ',
    title: [
      '雨声白噪音', '风声白噪音', '森林鸟鸣白噪音', '篝火燃烧白噪音','自然白噪音'
    ]
  },
  {
    name: ' 赛博哄睡 ',
    title: [
      'AI故事哄睡', '电子梦境旋律', '虚拟星空音效', '数字冥想之旅'
    ]
  }
];
const contentSections = ref<ContentSection[]>([]);

// 获取音乐数据
const getMusicData = async (tags: string[]) => {
  try {
    const tagsStr = tags.join(',');
    const response = await getMusicList(tagsStr);
    // @ts-ignore
    const musicList = response.data;
    contentSections.value = tags.map(tag => {
      return {
        title: tag,
        // @ts-ignore
        list: musicList.filter((music: any) => music.tags === tag).map((music: any) => {
          return {
            id: music.musicId,
            name: music.name,
            singer: music.singer,
            album: music.album,
            url: `${process.env.BASE_URL}${music.url}`,
            cover: `${process.env.BASE_URL}${music.cover}`,
            duration: music.duration,
            isCollected: music.isCollected,
          } as MusicItem; // 明确类型
        })
      };
    });
  } catch (error) {
    console.error('音乐数据获取失败:', error);
  }
};

// 标签切换事件
const onTabChange = (tab: { index: number }) => {
  currentTab.value = tab.index;
  getMusicData(tabList[currentTab.value].title);
};

// 查看更多
const handleMore = (title: string) => {
  // 修改为跳转到 musicMore.vue 页面并传递标题 参数需要是响应式的
  uni.navigateTo({
    url: `/pages/music/musicMore?title=${title}`
  });
  console.log(`查看${title}更多内容`);
};

// 播放音频
const isSecondClick = ref(false);

// 假设第一个点击事件是 playAudio
const playAudio = (item: MusicItem, title: string) => {
  // 修改为跳转到 musicPlaying.vue 页面并传递音乐id和title
  uni.navigateTo({
    url: `/pages/music/musicPlaying?id=${item.id}&title=${title}` // 传递id和title
  });
  console.log(`播放音频：${item.name}`);
};

// 格式化时长
const formatDuration = (seconds: number) => {
  const minutes = Math.floor(seconds / 60);
  const remainingSeconds = seconds % 60;
  return `${minutes}分${remainingSeconds}秒`;
};

// 收藏音乐
const collect = async (item: MusicItem) => {
  try {
    const response = await toggleCollect(item.id);
    // @ts-ignore
      // 创建一个新的 contentSections 数组
      const newContentSections = contentSections.value.map(section => {
        return {
          ...section,
          list: section.list.map(music => {
            if (music.id === item.id) {
              // 创建一个新的音乐对象，更新 isCollected 属性
              return {
                ...music,
                isCollected: music.isCollected === 1 ? 0 : 1
              };
            }
            return music;
          })
        };
      });
      // 更新 contentSections
      contentSections.value = newContentSections;
    
  } catch (error) {
    console.error('收藏操作失败:', error);
  }
};

// 页面显示时获取数据
onShow(() => {
  getMusicData(tabList[currentTab.value].title);
});
</script>

<style lang="scss" scoped>
.page {
  padding: 0 20rpx;
  margin: 20rpx;
  min-height: 110vh;
}

.content-section {
  padding: 20rpx;
}

.section {
  margin-bottom: 40rpx;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20rpx;
}

.section-title {
  color: #121211; 
  font-size: 48rpx; 
}

.more-btn {
  color: #131312; 
  font-size: 32rpx; 
}

.cover-img {
  width: 100%;
  height: 400rpx;
  border-radius: 20rpx;
}

.item-cover {
  position: relative;
}

.play-icon {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

.item-info {
  padding: 15rpx 0;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.item-name {
  font-size: 28rpx;
  margin-bottom: 10rpx;
}

.item-duration {
  color: #b2b2ac;
  font-size: 24rpx;
}
</style>